package com.example.downloader.http;

import android.util.Log;

import com.example.downloader.model.DownloadCallback;
import com.example.downloader.model.DownloadTask;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;

import okhttp3.Call;
import okhttp3.Response;

/**
 * Created by Administrator on 2017/11/22.
 */

class SimpleOkHttpDownloadTask extends DownloadTask<Response> {
    public SimpleOkHttpDownloadTask(DownloadCallback callbck) {
        super(callbck);
    }

    


    @Override
    protected Response doInBackground2(String... params) throws Throwable {
        Call call = OkHttpUtil.downloadFile(params[0], new ProgressRequestListener() {
            @Override
            public void onRequestProgress(long bytesWritten, long contentLength) {
                publishProgress(PROGRESS, 100, (int) ((double) bytesWritten / contentLength * 100));
            }
        });
        Response response = call.execute();
        final String filePath = params[1];
        File file = new File(filePath);
        if (file.exists())
            file.delete();
        InputStream is = response.body().byteStream();
        FileOutputStream fos = new FileOutputStream(file);
        int len = 0;
        byte[] buffer = new byte[2048];
        while (-1 != (len = is.read(buffer))) {
            fos.write(buffer, 0, len);
        }
        fos.flush();
        fos.close();
        is.close();
        return response;
    }


}
